package com.ruicar.afs.cloud.basic.common.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.basic.api.dto.LprQueryDto;
import com.ruicar.afs.cloud.basic.api.product.feign.ProductServiceFeign;
import com.ruicar.afs.cloud.basic.common.condition.DeductionInfoChildCondition;
import com.ruicar.afs.cloud.basic.common.condition.DeductionInfoCondition;
import com.ruicar.afs.cloud.basic.common.condition.QueryCustInfoMultipleCondition;
import com.ruicar.afs.cloud.basic.common.entity.*;
import com.ruicar.afs.cloud.basic.common.service.*;
import com.ruicar.afs.cloud.basic.common.vo.RepaymentPlanVo;
import com.ruicar.afs.cloud.basic.detail.vo.RentInfoVO;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.enums.*;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import com.ruicar.afs.cloud.common.vo.ChangePlanSyncDataRequestVo;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author: Lee
 * @date: 2020/5/11 19:39
 * @description: 合同还款计划表相关增删改查
 */
@Slf4j
@RestController
@RequestMapping("/repaymentPlanInfo")
@AllArgsConstructor
public class BasicRepaymentPlanController {

    private final BasicPenaltyInterestDetailsService basicPenaltyInterestDetailsService;
    private final BasicExpenseRecordDetailService basicExpenseRecordDetailService;
    private final BasicAssetsRepaymentPlanService basicAssetsRepaymentPlanService;
    private final BasicContractCustRelationService basicContractCustRelationService;
    private final BasicPenaltyInterestService basicPenaltyInterestService;
    private final BasicFinancialAgreementService basicFinancialAgreementService;
    private final BasicRepaymentPlanService basicRepaymentPlanService;
    private final BasicExpenseRecordService basicExpenseRecordService;
    private final BasicProductParamService basicProductParamService;
    private final BasicCustBaseInfoService basicCustBaseInfoService;
    private final BasicMainInfoService basicMainInfoService;
    private final BasicCarDetailsService basicCarDetailsService;
    private final BasicReceiptDealDetailsService basicReceiptDealDetailsService;
    private final ProductServiceFeign productServiceFeign;

    @ApiOperation(value = "根据合同号码查询还款计划表")
    @PostMapping("/getRepaymentPlanInfoList")
    public IResponse<BasicRepaymentPlan> getRepaymentPlanInfoList(@RequestParam("contractNo") String contractNo) {
        List<BasicRepaymentPlan> basicRepaymentPlan = basicRepaymentPlanService.list(Wrappers.<BasicRepaymentPlan>lambdaQuery().
                eq(BasicRepaymentPlan::getContractNo, contractNo).orderByAsc(BasicRepaymentPlan::getTermNo));
        return IResponse.success(basicRepaymentPlan);
    }


    /**
     * Cms接口聚合层使用  <6.8 获取还款计划>
     * 合同明细查询页面 当期、还款计划表两个页面也使用此接口
     * @param contractNo
     * @return
     */
    @ApiOperation(value = "根据合同号码查询还款计划表(含逾期天数)")
    @PostMapping("/getRepaymentPlanList")
    public IResponse<RepaymentPlanVo> getRepaymentPlanList(@RequestParam("contractNo") String contractNo) {
        if (EmptyUtils.isEmpty(contractNo)) {
            return IResponse.fail("合同号码不能为空！");
        }

        BasicMainInfo basicMainInfo = basicMainInfoService.getOne(Wrappers.<BasicMainInfo>lambdaQuery().eq(BasicMainInfo::getContractNo, contractNo));
        if (EmptyUtils.isEmpty(basicMainInfo)) {
            return IResponse.fail("没有查询到该合同信息，或者该合同不属于多品系统！");
        }

        BasicFinancialAgreement basicFinancialAgreement = new BasicFinancialAgreement();

        List<BasicCarDetails> basicCarDetails = basicCarDetailsService.list(Wrappers.<BasicCarDetails>lambdaQuery().eq(BasicCarDetails::getContractNo, contractNo));

        List<BasicFinancialAgreement> basicFinancialAgreements = basicFinancialAgreementService.list(Wrappers.<BasicFinancialAgreement>lambdaQuery()
                .eq(BasicFinancialAgreement::getContractNo, contractNo));
        basicFinancialAgreement = basicFinancialAgreement.sum(basicFinancialAgreements);

        BasicProductParam basicProductParam = basicProductParamService.getOne(Wrappers.<BasicProductParam>lambdaQuery()
                .eq(BasicProductParam::getContractNo, contractNo)
                .eq(BasicProductParam::getAtomKey, ProductAtomEnum.RATE_TYPE)
                .eq(BasicProductParam::getProductId, basicMainInfo.getProductId()));
        BasicContractCustRelation basicContractCustRelation = basicContractCustRelationService.getOne(Wrappers.<BasicContractCustRelation>lambdaQuery().
                eq(BasicContractCustRelation::getContractNo, contractNo)
                .eq(BasicContractCustRelation::getCustRole, AfsEnumUtil.key(PersonRoleTypeEnum.MAIN_PERSON)));
        if (EmptyUtils.isEmpty(basicContractCustRelation)) {
            return IResponse.fail("没有查询到客户信息！");
        }
        BasicCustBaseInfo basicCustBaseInfo = basicCustBaseInfoService.getOne(Wrappers.<BasicCustBaseInfo>lambdaQuery().
                eq(BasicCustBaseInfo::getCustNo, basicContractCustRelation.getCustNo()));
        if (EmptyUtils.isEmpty(basicCustBaseInfo)) {
            return IResponse.fail("没有查询到客户信息！");
        }
        List<BasicRepaymentPlan> basicRepaymentPlanList = basicRepaymentPlanService.list(Wrappers.<BasicRepaymentPlan>lambdaQuery().
                eq(BasicRepaymentPlan::getContractNo, contractNo).orderByAsc(BasicRepaymentPlan::getTermNo));

        List<RentInfoVO> rentInfoVOS = basicRepaymentPlanService.queryRepaymentInfo(contractNo, null);

        BigDecimal rent = new BigDecimal(0);
        List<BasicReceiptDealDetails> basicReceiptDealDetails = basicReceiptDealDetailsService.list(Wrappers.<BasicReceiptDealDetails>lambdaQuery()
                .eq(BasicReceiptDealDetails::getContractNo, contractNo).in(BasicReceiptDealDetails::getReceiptType, FeeTypeEnum.advanceSettle, FeeTypeEnum.urge, FeeTypeEnum.changeCost));
        for (BasicRepaymentPlan basicRepaymentPlan : basicRepaymentPlanList) {
            //未还租金累加
            if (RepaymentStatusEnum.UNPAID == basicRepaymentPlan.getStatus() || RepaymentStatusEnum.OVERDUE == basicRepaymentPlan.getStatus()) {
                rent = rent.add(basicRepaymentPlan.getReceivableRent().subtract(basicRepaymentPlan.getActualRent()));
            }
            //把费用金额，挂到还款计划上
            String due = DateUtil.format(basicRepaymentPlan.getDueDate(), "yyyy-mm-dd");
            for (BasicReceiptDealDetails detail : basicReceiptDealDetails) {
                String detailDate = DateUtil.format(detail.getCreateTime(), "yyyy-mm-dd");
                if (due.equals(detailDate)) {
                    basicRepaymentPlan.setCostFree(basicRepaymentPlan.getCostFree().add(detail.getDealAmt()));
                }
            }
            //计算剩余应还本金、剩余应还利息、剩余应还租金
            basicRepaymentPlan.setUnpaidRent(basicRepaymentPlan.getReceivableRent().subtract(basicRepaymentPlan.getActualRent()));
            basicRepaymentPlan.setTotalUnpaidPrinciple(basicRepaymentPlan.getReceivablePrinciple().subtract(basicRepaymentPlan.getActualPrinciple()));
            basicRepaymentPlan.setTotalUnpaidInterest(basicRepaymentPlan.getReceivableInterest().subtract(basicRepaymentPlan.getActualInterest()));

        }
        RepaymentPlanVo repaymentPlanVo = new RepaymentPlanVo();
        repaymentPlanVo.setContractNo(contractNo);
        repaymentPlanVo.setCustName(basicCustBaseInfo.getCustName());
        repaymentPlanVo.setLoanDeadline(basicRepaymentPlanList.size());
        repaymentPlanVo.setLoanAmt(basicFinancialAgreement.getLoanAmt());
        repaymentPlanVo.setCustRate(basicFinancialAgreement.getCustRate());
        repaymentPlanVo.setRepaymentPlan(basicRepaymentPlanList);

        if (EmptyUtils.isEmpty(basicProductParam)) {
            return IResponse.fail("没有查询到产品的利率信息！");
        }

        if (AfsEnumUtil.key(YesOrNoNumEnum.YES).equals(basicProductParam.getAtomValue())) {
            //浮动利率
            LprQueryDto dto = new LprQueryDto();
            dto.setLoanPeriodStart(basicRepaymentPlanList.size());
            dto.setLoanPeriodEnd(basicRepaymentPlanList.size());
            IResponse response = productServiceFeign.getLprNew(dto);
            if (CommonConstants.SUCCESS.equals(response.getCode())) {
                repaymentPlanVo.setBaseRate(new BigDecimal(String.valueOf(response.getData())));
            } else {
                repaymentPlanVo.setBaseRate(null);
            }
            repaymentPlanVo.setPeroid(0);
            repaymentPlanVo.setPlanMode("1");
            repaymentPlanVo.setProfitMargin(basicFinancialAgreement.getBasicPoint());
        } else {
            //固定利率
            repaymentPlanVo.setPlanMode("0");
            repaymentPlanVo.setStartDate(basicMainInfo.getStartDate());
            repaymentPlanVo.setEndDate(basicMainInfo.getEndDate());
            repaymentPlanVo.setProductName(basicMainInfo.getProductName());
            repaymentPlanVo.setPaymentFrequency("Monthly");
            repaymentPlanVo.setTotalInterest(rentInfoVOS.get(0).getInterestTotal());
            repaymentPlanVo.setTotalRemain(rent);
            repaymentPlanVo.setVehicleDesc(basicCarDetails.get(0).getBrandName());
        }

        return IResponse.success(repaymentPlanVo);
    }

    @ApiOperation(value = "根据合同号码查询租金统计明细")
    @PostMapping("/repayPlanDetailValidParam")
    public IResponse repayPlanDetailValidParam(@RequestParam(value = "contractNo", required = false) String contractNo, @RequestParam(value = "contractId", required = false) String contractId) {
        if ((EmptyUtils.isEmpty(contractNo) || ("null".equals(contractNo))) &&
                ((EmptyUtils.isEmpty(contractId)) || "null".equals(contractId))) {
            return IResponse.fail("合同号和合同id不能同时为空");
        }
        if ((EmptyUtils.isEmpty(contractNo) || "null".equals(contractNo))
                && EmptyUtils.isNotEmpty(contractId) && !"null".equals(contractId)) {
            BasicMainInfo basicMainInfo = basicMainInfoService.getById(contractId);
            if (EmptyUtils.isEmpty(basicMainInfo)) {
                return IResponse.fail("合同Id:" + contractId + ",没有查询到相关数据，或此合同id不属于多品系统");
            }
            contractNo = basicMainInfo.getContractNo();
        }
        List<RentInfoVO> rentInfos = basicRepaymentPlanService.queryRepaymentInfo(contractNo, null);
        if (EmptyUtils.isEmpty(rentInfos)) {
            return IResponse.fail("未查询到相关有效信息");
        }
        for (RentInfoVO rentInfo : rentInfos) {
            BasicExpenseRecord basicExpenseRecord = basicExpenseRecordService.getOne(Wrappers.<BasicExpenseRecord>lambdaQuery()
                    .eq(BasicExpenseRecord::getContractNo, rentInfo.getContractNo())
                    .eq(BasicExpenseRecord::getCostType, FeeTypeEnum.penalty));
            if (EmptyUtils.isEmpty(basicExpenseRecord)) {
                rentInfo.setOverdueInterest(BigDecimal.ZERO);
                rentInfo.setOverdueTotal(BigDecimal.ZERO);
                rentInfo.setOverdueMoney(BigDecimal.ZERO);
            } else {
                rentInfo.setOverdueInterest(basicExpenseRecord.getRemainingAmt());
                rentInfo.setOverdueTotal(rentInfo.getTotalPayment().add(rentInfo.getOverdueInterest()));
                rentInfo.setOverdueMoney(rentInfo.getOverdueTotal());
            }
        }

        return IResponse.success(rentInfos);
    }


    @ApiOperation(value = "根据合同号码查询租金统计明细")
    @PostMapping("/repayPlanDetail")
    public IResponse repayPlanDetail(@RequestParam(value = "contractNo", required = false) String contractNo, @RequestParam(value = "contractId", required = false) String contractId) {
//        if ((EmptyUtils.isEmpty(contractNo) || ("null".equals(contractNo))) &&
//                ((EmptyUtils.isEmpty(contractId)) || "null".equals(contractId))) {
//            return IResponse.fail("合同号和合同id不能同时为空");
//        }
        if ((EmptyUtils.isEmpty(contractNo) || "null".equals(contractNo))
                && EmptyUtils.isNotEmpty(contractId) && !"null".equals(contractId)) {
            BasicMainInfo basicMainInfo = basicMainInfoService.getById(contractId);
            if (EmptyUtils.isEmpty(basicMainInfo)) {
                return IResponse.fail("合同Id:" + contractId + ",没有查询到相关数据，或此合同id不属于多品系统");
            }
            contractNo = basicMainInfo.getContractNo();
        }
        List<RentInfoVO> rentInfos = basicRepaymentPlanService.queryRepaymentInfo(contractNo, YesOrNoEnum.yes.name());
        if (EmptyUtils.isEmpty(rentInfos)) {
            return IResponse.fail("未查询到相关有效信息");
        }
        for (RentInfoVO rentInfo : rentInfos) {
            BasicExpenseRecord basicExpenseRecord = basicExpenseRecordService.getOne(Wrappers.<BasicExpenseRecord>lambdaQuery()
                    .eq(BasicExpenseRecord::getContractNo, rentInfo.getContractNo())
                    .eq(BasicExpenseRecord::getCostType, FeeTypeEnum.penalty));
            if (EmptyUtils.isEmpty(basicExpenseRecord)) {
                rentInfo.setOverdueInterest(BigDecimal.ZERO);
                rentInfo.setOverdueTotal(BigDecimal.ZERO);
                rentInfo.setOverdueMoney(BigDecimal.ZERO);
            } else {
                rentInfo.setOverdueInterest(basicExpenseRecord.getRemainingAmt());
                rentInfo.setOverdueTotal(rentInfo.getTotalPayment().add(rentInfo.getOverdueInterest()));
                rentInfo.setOverdueMoney(rentInfo.getOverdueTotal());
            }
        }

        return IResponse.success(rentInfos);
    }

    @ApiOperation(value = "还款及扣款信息查询接口")
    @PostMapping("/deductionInfo")
    public IResponse<DeductionInfoCondition> deductionInfo(@RequestParam(value = "certNo") String certNo) {
        QueryCustInfoMultipleCondition condition = new QueryCustInfoMultipleCondition();
        condition.setCertNo(certNo);
        List<DeductionInfoChildCondition> deductionInfoChildConditions = basicRepaymentPlanService.deductionInfo(condition);
        DeductionInfoCondition deductionInfoCondition = new DeductionInfoCondition();
        for (DeductionInfoChildCondition cd : deductionInfoChildConditions) {
            if (ContractStatusEnum.overdue.name().equals(cd.getPayStatus())) {
                deductionInfoCondition.setOverdueStatus("1");
            } else {
                deductionInfoCondition.setOverdueStatus("2");
            }
        }
        deductionInfoCondition.setDeductionInfo(deductionInfoChildConditions);
        deductionInfoCondition.setCount(deductionInfoChildConditions.size());

        return IResponse.success(deductionInfoCondition);
    }

    @ApiOperation(value = "还款日变更，更新还款日")
    @PostMapping("/updateRepaymentPlan")
    public IResponse<Boolean> updateRepaymentPlan(@RequestBody ChangePlanSyncDataRequestVo data) {
        LambdaQueryWrapper<BasicRepaymentPlan> wrapper = Wrappers.<BasicRepaymentPlan>lambdaQuery();
        wrapper.eq(BasicRepaymentPlan::getContractNo, data.getContractNo());
        wrapper.eq(BasicRepaymentPlan::getStatus, RepaymentStatusEnum.UNPAID);
        wrapper.and(wrap -> wrap.eq(BasicRepaymentPlan::getActualRent, 0)
                .or()
                .isNull(BasicRepaymentPlan::getActualRent).or().eq(BasicRepaymentPlan::getActualRent, ""));
        wrapper.orderByAsc(BasicRepaymentPlan::getTermNo);


        LambdaQueryWrapper<BasicAssetsRepaymentPlan> wrapperAsset = Wrappers.<BasicAssetsRepaymentPlan>lambdaQuery();
        wrapperAsset.eq(BasicAssetsRepaymentPlan::getContractNo, data.getContractNo());
        wrapperAsset.eq(BasicAssetsRepaymentPlan::getStatus, RepaymentStatusEnum.UNPAID);
        wrapperAsset.and(wrap -> wrap.eq(BasicAssetsRepaymentPlan::getActualRent, 0)
                .or()
                .isNull(BasicAssetsRepaymentPlan::getActualRent).or().eq(BasicAssetsRepaymentPlan::getActualRent, ""));
        wrapperAsset.orderByAsc(BasicAssetsRepaymentPlan::getTermNo);
        List<BasicRepaymentPlan> basicRepaymentPlans = basicRepaymentPlanService.list(wrapper);
        List<BasicAssetsRepaymentPlan> basicAssetsRepaymentPlans = basicAssetsRepaymentPlanService.list(wrapperAsset);
        basicRepaymentPlans.remove(0);
        basicAssetsRepaymentPlans.remove(0);
        if (EmptyUtils.isNotEmpty(basicRepaymentPlans)) {
            if (DateUtil.isSameDay(DateUtil.endOfMonth(data.getDueDate()), data.getDueDate())) {
                //如果新的变更日是月末，那么变更后的还款日是每个月的最后一天
                for (BasicRepaymentPlan plan : basicRepaymentPlans) {
                    DateTime dt = DateUtil.endOfMonth(plan.getDueDate());
                    plan.setDueDate(DateUtil.parse(DateUtil.format(dt, "yyyy-MM-dd"), "yyyy-MM-dd"));
                    //更新资产还款计划
                    for (BasicAssetsRepaymentPlan assetsPlan : basicAssetsRepaymentPlans) {
                        if (assetsPlan.getTermNo() == plan.getTermNo()) {
                            assetsPlan.setDueDate(DateUtil.parse(DateUtil.format(dt, "yyyy-MM-dd"), "yyyy-MM-dd"));
                        }
                    }
                }
            } else {
                for (BasicRepaymentPlan plan : basicRepaymentPlans) {
                    //取出新的日期的day
                    String dd = DateUtil.format(data.getDueDate(), "dd");
                    Date due = plan.getDueDate();
                    String format = DateUtil.format(due, "yyyy-MM-dd");
                    //用新day替换原day
                    String newDate = format.substring(0, format.length() - 2) + dd;
                    DateTime newDueDate = DateUtil.parseDate(newDate);
                    //判断替换完的新day是否还在原月份中，如果不在，向前减一天
                    //举例：假如，新的变更日期是每月30号，替换完的日期为2018年11月30日、2018年12月30日、2019年1月30日、2019年2月30日，而2019年2月只有28天，则需要向前偏移2天
                    boolean in = DateUtil.isIn(newDueDate, DateUtil.beginOfMonth(due), DateUtil.endOfMonth(due));
                    while (!in) {
                        newDueDate = DateUtil.offsetDay(newDueDate, -1);
                        in = DateUtil.isIn(newDueDate, DateUtil.beginOfMonth(due), DateUtil.endOfMonth(due));
                    }
                    plan.setDueDate(newDueDate);

                    //更新资产还款计划
                    for (BasicAssetsRepaymentPlan assetsPlan : basicAssetsRepaymentPlans) {
                        if (assetsPlan.getTermNo() == plan.getTermNo()) {
                            assetsPlan.setDueDate(newDueDate);
                        }
                    }

                }

            }
            basicRepaymentPlanService.updateBatchById(basicRepaymentPlans);
        }
        BigDecimal b = BigDecimal.valueOf(0);
        if (data.getCostAmt().compareTo(b) != 0) {
            //新增费用数据
            //费用明细
            BasicExpenseRecordDetail basicExpenseRecordDetail = new BasicExpenseRecordDetail();
            basicExpenseRecordDetail.setContractNo(data.getContractNo());
            basicExpenseRecordDetail.setCostType(FeeTypeEnum.changeCost);
            basicExpenseRecordDetail.setEndDate(DateUtil.date());
            basicExpenseRecordDetail.setCostAmt(data.getCostAmt());
            basicExpenseRecordDetail.setRemainingAmt(data.getCostAmt());
            basicExpenseRecordDetail.setStatus(ExpenseStatusEnum.unsettle);
            basicExpenseRecordDetailService.save(basicExpenseRecordDetail);

            //费用汇总
            BasicExpenseRecord record = basicExpenseRecordService.getOne(Wrappers.<BasicExpenseRecord>lambdaQuery()
                    .eq(BasicExpenseRecord::getCostType, FeeTypeEnum.changeCost)
                    .eq(BasicExpenseRecord::getContractNo, data.getContractNo()));
            if (EmptyUtils.isEmpty(record)) {
                //如果之前没有，则增加一条
                BasicExpenseRecord basicExpenseRecord = new BasicExpenseRecord();
                BeanUtil.copyProperties(basicExpenseRecordDetail, basicExpenseRecord);
                basicExpenseRecordService.save(basicExpenseRecord);
            } else {
                //如果之前存在此费用，则在之前基础上相加
                record.setCostAmt(record.getCostAmt().add(data.getCostAmt()));
                record.setRemainingAmt(record.getCostAmt().subtract(record.getReceivedAmt().add(record.getExemptionAmt())));
                record.setStatus(ExpenseStatusEnum.unsettle);
                basicExpenseRecordService.updateById(record);
            }

            //费用流水
            BasicPenaltyInterestDetails basicPenaltyInterestDetails = new BasicPenaltyInterestDetails();
            basicPenaltyInterestDetails.setContractNo(data.getContractNo());
            basicPenaltyInterestDetails.setAmount(data.getCostAmt());
            basicPenaltyInterestDetails.setCostType(FeeTypeEnum.changeCost);
            basicPenaltyInterestDetails.setDate(DateUtil.date());
            basicPenaltyInterestDetails.setOperateType(CostDetailedTypeEnum.newArrears);
            basicPenaltyInterestDetailsService.save(basicPenaltyInterestDetails);
        }
        if (data.getExtraInterest().compareTo(b) != 0) {
            //新增费用额外利息数据
            //费用明细
            BasicExpenseRecordDetail expenseRecordDetail = new BasicExpenseRecordDetail();
            expenseRecordDetail.setContractNo(data.getContractNo());
            expenseRecordDetail.setEndDate(DateUtil.date());
            expenseRecordDetail.setStatus(ExpenseStatusEnum.unsettle);
            expenseRecordDetail.setCostType(FeeTypeEnum.changeExtraInterest);
            expenseRecordDetail.setCostAmt(data.getExtraInterest());
            expenseRecordDetail.setRemainingAmt(data.getExtraInterest());
            basicExpenseRecordDetailService.save(expenseRecordDetail);

            //费用汇总额外利息数据
            BasicExpenseRecord ExpenseRecord = basicExpenseRecordService.getOne(Wrappers.<BasicExpenseRecord>lambdaQuery()
                    .eq(BasicExpenseRecord::getCostType, FeeTypeEnum.changeExtraInterest)
                    .eq(BasicExpenseRecord::getContractNo, data.getContractNo()));
            if (EmptyUtils.isEmpty(ExpenseRecord)) {
                //如果之前没有，则增加一条
                BasicExpenseRecord expenseRecord = new BasicExpenseRecord();
                BeanUtil.copyProperties(expenseRecordDetail, expenseRecord);
                basicExpenseRecordService.save(expenseRecord);
            } else {
                //如果之前存在此费用，则在之前基础上相加
                ExpenseRecord.setCostAmt(ExpenseRecord.getCostAmt().add(data.getExtraInterest()));
                ExpenseRecord.setRemainingAmt(ExpenseRecord.getCostAmt().subtract(ExpenseRecord.getReceivedAmt().add(ExpenseRecord.getExemptionAmt())));
                ExpenseRecord.setStatus(ExpenseStatusEnum.unsettle);
                basicExpenseRecordService.updateById(ExpenseRecord);
            }

            //费用流水额外利息数据
            BasicPenaltyInterestDetails penaltyInterestDetails = new BasicPenaltyInterestDetails();
            penaltyInterestDetails.setContractNo(data.getContractNo());
            penaltyInterestDetails.setAmount(data.getExtraInterest());
            penaltyInterestDetails.setCostType(FeeTypeEnum.changeExtraInterest);
            penaltyInterestDetails.setDate(DateUtil.date());
            penaltyInterestDetails.setOperateType(CostDetailedTypeEnum.newArrears);
            basicPenaltyInterestDetailsService.save(penaltyInterestDetails);
        }
        return IResponse.success("更新成功");
    }


    @ApiOperation(value = "查询最近还款日信息（接口聚合用）")
    @PostMapping("/getDueDateNocushionDays")
    public IResponse<BasicMainInfo> getDueDateNocushionDays(@RequestParam("contractNo") String contractNo) {
        List<BasicRepaymentPlan> basicRepaymentPlanList = basicRepaymentPlanService.list(Wrappers.<BasicRepaymentPlan>lambdaQuery().
                eq(BasicRepaymentPlan::getContractNo, contractNo).eq(BasicRepaymentPlan::getStatus, RepaymentStatusEnum.UNPAID)
                .or().eq(BasicRepaymentPlan::getStatus, RepaymentStatusEnum.OVERDUE).orderByAsc(BasicRepaymentPlan::getTermNo));
        BasicMainInfo basicMainInfo = basicMainInfoService.getOne(Wrappers.<BasicMainInfo>lambdaQuery().eq(BasicMainInfo::getContractNo, contractNo));

        if (EmptyUtils.isEmpty(basicRepaymentPlanList) || EmptyUtils.isEmpty(basicMainInfo)) {
            return IResponse.fail("没有查询到有效数据");
        }
        basicMainInfo.setRepaymentDate(DateUtil.format(basicRepaymentPlanList.get(0).getDueDate(), "yyyy-MM-dd"));
        return new IResponse().setData(basicMainInfo);
    }


}
